//
//  PMNavigationController.m
//  DBAChain
//
//  Created by Evan on 2018/9/5.
//  Copyright © 2018 Evan. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "PMNavigationController.h"


static float ShadowScale = 0.94;

@interface PMNavigationController ()
{
    NSMutableArray*                 _captureQueue;
    UIImageView*                    _lastCaptureView;
    UIPanGestureRecognizer*         _panGesture;
    UIView*                         _shadowView;
    CGPoint                         _lastPt;
}

- (UIImage*)captureView:(UIView*)view;

- (float)getPercent:(UIView*)view move:(float)move;

- (void)addGesture;

- (void)removeGesture;

- (void)handlePanGesture:(UIPanGestureRecognizer*)recognizer;


@end

@implementation PMNavigationController
@synthesize stackInfo = _stackInfo;
@synthesize useMutilLayer = _useMutilLayer;

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        _useMutilLayer = YES;
        [self addGesture];
    }
    return self;
}

- (id)initWithRootViewController:(UIViewController *)rootViewController
{
    self = [super initWithRootViewController:rootViewController];
    if(self){
        _useMutilLayer = YES;
        [self addGesture];
    }
    return self;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if(_useMutilLayer){
        UIImage* captureImg = nil;
        if(self.tabBarController){
            captureImg = [self captureView:self.tabBarController.view];
        }
        else{
            captureImg = [self captureView:self.view];
        }
        if(captureImg){
            if(_captureQueue == nil){
                _captureQueue = [[NSMutableArray alloc] init];
            }
            [_captureQueue addObject:captureImg];
        }
    }
    if([viewController isKindOfClass:[PMViewController class]]){
        [(PMViewController*)viewController setIsPush:YES];
    }
    [super pushViewController:viewController animated:animated];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    if([self.viewControllers count] > 2){
        //倒数第二个
        id viewCtrl = [self.viewControllers objectAtIndex:[self.viewControllers count] - 2];
        if([viewCtrl isKindOfClass:[PMViewController class]]){
            [(PMViewController*)viewCtrl setIsPush:NO];
        }
    }
    UIViewController* viewController = [super popViewControllerAnimated:animated];
    if(viewController && [_captureQueue count] >= 1){
        [_captureQueue removeLastObject];
    }
    return viewController;
}

//- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    if([viewController isKindOfClass:[PMViewController class]]){
//        [(PMViewController*)viewController setIsPush:NO];
//    }
//    NSArray* viewControllers = [super popToViewController:viewController animated:animated];
//    if([viewControllers count] <= [_captureQueue count]){
//        for(NSUInteger i = 0; i < [viewControllers count]; ++i){
//            [_captureQueue removeLastObject];
//        }
//    }
//    return viewControllers;
//}

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
{
    if([self.viewControllers count] > 0){
        
        if([[self.viewControllers objectAtIndex:0] isKindOfClass:[PMViewController class]]){
            [(PMViewController*)[self.viewControllers objectAtIndex:0] setIsPush:NO];
        }
    }
    NSArray* viewControllers = [super popToRootViewControllerAnimated:animated];
    if([viewControllers count] <= [_captureQueue count]){
        for(NSUInteger i = 0; i < [viewControllers count]; ++i){
            [_captureQueue removeLastObject];
        }
    }
    return viewControllers;
}

#pragma mark public method

-(void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion{
    [super presentViewController:viewControllerToPresent animated:flag completion:completion];
    PMViewController *vc = (PMViewController *)self.topViewController;
    [vc setIsPush:NO];
}

- (void)setUseMutilLayer:(BOOL)useMutilLayer
{
    _useMutilLayer = useMutilLayer;
    if(_useMutilLayer && _panGesture == nil){
        [self addGesture];
    }
    else if(_panGesture){
        [self removeGesture];
    }
}

- (void)locateToViewController:(UIViewController*)viewController animated:(BOOL)animated
{
    if(self.topViewController != viewController){
        if([self.viewControllers containsObject:viewController]){
            [self popToViewController:viewController animated:animated];
        }
        else{
            [self pushViewController:viewController animated:animated];
        }
    }
}

#pragma mark private method
- (UIImage*)captureView:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (float)getPercent:(UIView*)view move:(float)move
{
    return (view.frame.origin.x + move) / view.frame.size.width;
}

- (void)addGesture
{
    if(_useMutilLayer){
        //平移
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
        
        if([self.viewControllers count] < 2){
            [self.view addGestureRecognizer:_panGesture];
        }
        
        _shadowView = [[UIView alloc] init];
        [_shadowView setBackgroundColor:[UIColor blackColor]];
        [_shadowView setAlpha:0.0];
    }
}

- (void)removeGesture
{
    if(_panGesture){
        [self.view removeGestureRecognizer:_panGesture];
    }
}

- (void)handlePanGesture:(UIPanGestureRecognizer*)recognizer
{
    if([self.viewControllers count] < 2){
        return;
    }
    UIPanGestureRecognizer* panGes = recognizer;
    CGPoint point = [panGes translationInView:self.topViewController.view];
    switch (panGes.state) {
        case UIGestureRecognizerStateBegan:
        {
            if(_lastCaptureView == nil){
                UIImage* captureImgae = [_captureQueue lastObject];
                _lastCaptureView = [[UIImageView alloc] initWithImage:captureImgae];
            }
            else{
                [_lastCaptureView setImage:[_captureQueue lastObject]];
            }
            [_lastCaptureView setTransform:CGAffineTransformMakeScale(ShadowScale, ShadowScale)];
            [_lastCaptureView addSubview:_shadowView];
            [_shadowView setAlpha:0.2];
            [self.view.superview setBackgroundColor:[UIColor grayColor]];
            [self.view.superview insertSubview:_lastCaptureView belowSubview:self.view];
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            if(self.view.frame.origin.x + (point.x - _lastPt.x) > 0){
                [self.view setFrame:CGRectMake(self.view.frame.origin.x + (point.x - _lastPt.x),
                                               self.view.frame.origin.y,
                                               self.view.frame.size.width,
                                               self.view.frame.size.height)];
                float percent = [self getPercent:self.view move:(point.x - _lastPt.x)];
                [_shadowView setAlpha:0.2 *(1 - percent)];
                [_lastCaptureView setTransform:CGAffineTransformMakeScale(ShadowScale + 0.02 * percent,
                                                                          ShadowScale + 0.02 * percent)];
            }
            _lastPt = point;
            break;
        }
        case UIGestureRecognizerStateEnded:
        {
            _lastPt = CGPointZero;
            __block BOOL pop = NO;
            CGRect frame = CGRectZero;
            float alpha = 0.0;
            float scale = 1.0;
            if(self.view.frame.origin.x > self.view.frame.size.width / 15){
                frame = CGRectMake(self.view.frame.size.width,
                                   self.view.frame.origin.y,
                                   self.view.frame.size.width,
                                   self.view.frame.size.height);
                alpha = 0.0;
                scale = 1.0;
                pop = YES;
            }
            else{
                frame = CGRectMake(0.0,
                                   self.view.frame.origin.y,
                                   self.view.frame.size.width,
                                   self.view.frame.size.height);
                alpha = 0.3;
                scale = ShadowScale;
                
            }
            __weak PMNavigationController* weakSelf = self;
            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationOptionCurveLinear
                             animations:^{
                                 [weakSelf.view setFrame:frame];
                                 [_shadowView setAlpha:alpha];
                                 [_lastCaptureView setTransform:CGAffineTransformMakeScale(scale, scale)];
                             }
                             completion:^(BOOL finished){
                                 [weakSelf.view setFrame:CGRectMake(0.0,
                                                                    weakSelf.view.frame.origin.y,
                                                                    weakSelf.view.frame.size.width,
                                                                    weakSelf.view.frame.size.height)];
                                 [_shadowView removeFromSuperview];
                                 [_lastCaptureView removeFromSuperview];
                                 _lastCaptureView = nil;
                                 if(pop){
                                     [weakSelf popViewControllerAnimated:NO];
                                 }
                             }];
            break;
        }
        default:
            break;
    }
}

@end
